import { Modal } from 'antd';
import { FolderOutlined, FileOutlined } from '@ant-design/icons';

import _ from 'lodash'
import dayjs from 'dayjs';

export function assert(condition, msg) {
  if (!condition) console.error(msg || `[ASSERT]: ${condition} is a falsy value.`)
};

export const __DEV__ = process.env.NODE_ENV === 'development';

// 处理inlineStr单元格
function isInlineStringCT(ct) {
  let isIs = ct !== null && ct.t === "inlineStr" && ct.s !== null && ct.s.length > 0;
  return isIs;
}
function getInlineStringNoStyle(ct) {
  if (isInlineStringCT(ct)) {
    let strings = ct.s, value = "";
    for (let i = 0; i < strings.length; i++) {
      let strObj = strings[i];
      if (strObj.v != null) {
        value += strObj.v;
      }
    }
    return value;
  }

  return "";
}

function getLuckysheetData() {
  const luckysheet = window.luckysheet;
  const chartmix = window.chartmix;
  const sheets = luckysheet.getAllSheets();
  sheets.forEach((item, index) => {
    delete item.data;
    if (item.chart) {
      item.chart.forEach((chart, i) => {
        item.chart[i] = {
          ...item.chart[i],
          chartOptions: { ...chartmix.default.getChartJson(chart.chart_id) }
        }
        let div = document.getElementById(chart.chart_id + '_c');
        if (div.style) {
          item.chart[i].left = parseInt(div.style.left)
          item.chart[i].top = parseInt(div.style.top)
          item.chart[i].width = parseInt(div.style.width)
          item.chart[i].height = parseInt(div.style.height)
        }
      })
    }
  });
  return sheets;
}

export const SheetUtil = {
  getLuckysheetData,
  getInlineStringNoStyle,
  isInlineStringCT,
  getCellValue(v) {
    const ct = v.ct;
    let value = v.v;
    if (isInlineStringCT(ct)) {
      value = getInlineStringNoStyle(ct);
    }
    return value;
  }
};

const TIME_FORMAT = "HH:mm";

// const basedate = new Date(1899, 11, 31, 0, 0, 0);
// const dnthresh = basedate.getTime();
const base1904 = new Date(1900, 2, 1, 0, 0, 0);

// function datenum(v, date1904) {
//     var epoch = v.getTime();
//     if (date1904) epoch -= 1462 * 24 * 60 * 60 * 1000;
//     return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
// }

export function datenum_local(v, date1904) {
  var epoch = Date.UTC(v.getFullYear(), v.getMonth(), v.getDate(), v.getHours(), v.getMinutes(), v.getSeconds());
  var dnthresh_utc = Date.UTC(1899, 11, 31, 0, 0, 0);

  if (date1904) epoch -= 1461 * 24 * 60 * 60 * 1000;
  else if (v >= base1904) epoch += 24 * 60 * 60 * 1000;
  return (epoch - dnthresh_utc) / (24 * 60 * 60 * 1000);
}

function numdate(v) {
  var dnthresh_utc = Date.UTC(1899, 11, 31, 0, 0, 0);

  var epoch = v * 24 * 60 * 60 * 1000 + dnthresh_utc;
  var out = new Date();
  out.setTime(epoch);
  if (out > base1904) {
    epoch -= 24 * 60 * 60 * 1000;
    out.setTime(epoch);
  }
  return out;
}


export const DayUtil = {

  dayjsFromMins(miuntes) {
    const m = miuntes && dayjs.unix(miuntes * 60).utc();
    return m;
  },

  formatTimeDelta(miuntes) {
    if (_.isNil(miuntes)) {
      return '';
    }
    const sign = miuntes >= 0;
    const time = dayjs.unix(Math.abs(miuntes) * 60).utc();
    return (sign ? '' : '-') + time.format(TIME_FORMAT);
  },


  /**
   * 转换成luckysheet中使用的时间数据
   */
  dateToDays: datenum_local,
  daysToDate: numdate,
}

export const MyModal = {
  warning(obj) {
    Modal.warning({ ...obj, zIndex: 1020 });
  },
  confirm(obj) {
    Modal.confirm({ ...obj, zIndex: 1020 });
  }
}

// Javascript计算字符串长度（中文算两个字符）
export function getStringLength(str) {
  var len = str.length;
  var reLen = 0;
  for (var i = 0; i < len; i++) {
    if (str.charCodeAt(i) < 27 || str.charCodeAt(i) > 126) {
      // 全角    
      reLen += 2;
    } else {
      reLen++;
    }
  }
  return reLen;
}


function buildDeviceNode(device, checkable) {
  const node = {
    title: device.device_desc,
    key: `DEVICE-${device.device_id}`,
    icon: <FileOutlined />,
    checkable: checkable,
    data: device,
  };
  return node;
}

function buildBayNode(bay, checkable) {
  const node = {
    title: bay.bay_desc,
    key: `BAY-${bay.bay_id}`,
    icon: <FolderOutlined />,
    checkable: checkable,
    data: bay,
    children: bay.device_list && bay.device_list.map(d => buildDeviceNode(d, checkable))
  };
  return node;
}

// function buildTerminalNode(t) {
//   const node = {
//     title: t.terminal_desc,
//     key: `TERMINAL-${t.terminal_no}`,
//     icon: <FileOutlined />,
//     checkable: false,
//     data: t,
//   };
//   return node;
// }

export function buildStationNode(station, deviceCheckable = false) {
  let children;
  // for report api request_get_terminal_list
  // if (station.terminal_list) {
  //   children = station.terminal_list.map(b => buildTerminalNode(b));
  // }
  // for curve api
  if (station.bay_list) {
    children = station.bay_list.map(b => buildBayNode(b, deviceCheckable));
  }

  const node = {
    title: station.station_desc,
    key: `STATION-${station.station_id}`,
    icon: <FolderOutlined />,
    checkable: false,
    children: children,
    data: station,
  };
  return node;
}

export function buildMeasurementNode(point) {
  const node = {
    title: point.point_desc,
    key: `POINT-${point.point_id}`,
    checkable: true,
    isLeaf: true,
    data: point,
  };
  return node;
}

export function findNode(nodes, key) {
  for (const n of nodes) {
    if (n.key === key) {
      return n;
    }

    if (n.children) {
      const ret = findNode(n.children, key);
      if (ret) {
        return ret;
      }
    }
  }
}

export function findAncestorNodes(nodes, key) {
  const ancestors = [];

  function dfs(nodes, ancestors) {
    for (const n of nodes) {
      if (n.key === key) {
        return true;
      }

      if (n.children) {
        const ret = dfs(n.children, ancestors);
        if (ret) {
          ancestors.unshift(n);
          return true;
        }
      }
    }
    return false;
  }

  dfs(nodes, ancestors);
  return ancestors;
}